﻿using System;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Xml;
using Jerry.DroidBuilder.ThemeEditor.Controls;

namespace Jerry.DroidBuilder.ThemeEditor.Converters
{
    public class DrawableValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var drawable = value as string;
            var state = parameter as string;
            var drawableXml = string.Empty;

            if (null == drawable || (!drawable.StartsWith("@")
                && !drawable.EndsWith(".xml", StringComparison.InvariantCultureIgnoreCase)))
            {
                return value;
            }

            if (drawable.StartsWith("@"))
            {
                drawable = GetDrawablePath(drawable);
            }

            if (drawable.EndsWith(".xml"))
            {
                drawableXml = drawable;
                drawable = GetDrawable(drawable, state, culture);
            }

            if (drawable.StartsWith("@"))
            {
                return null;
            }

            return new DrawableInfo(drawable, drawableXml);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        private string GetDrawablePath(string value)
        {
            var ary = value.Split('/');
            var drawables = Directory.GetFiles(@"D:\Jerry\android\apktool\framework-res\res", string.Format("{0}.*", ary[1]), SearchOption.AllDirectories);

            if (drawables.Length <= 0)
            {
                return value;
            }

            return drawables[0];
        }

        private string GetDrawable(string drawableXml, string state, CultureInfo culture)
        {
            const string DEFAULT_XPATH = "/selector/item[last()]/@android:drawable";

            var doc = new XmlDocument();
            var xpath = DEFAULT_XPATH;

            XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(doc.NameTable);
            xmlnsManager.AddNamespace("android", "http://schemas.android.com/apk/res/android");

            doc.Load(drawableXml);

            if (!string.IsNullOrEmpty(state))
            {
                xpath = "/selector/item[@android:" + state + "='true']/@android:drawable";
            }

            var attr = doc.SelectSingleNode(xpath, xmlnsManager);

            if (null == attr && xpath != DEFAULT_XPATH)
            {
                attr = doc.SelectSingleNode(DEFAULT_XPATH, xmlnsManager);
            }

            return GetDrawablePath(attr.Value);
            //return _pathConverter.Convert(attr.Value, typeof(string), null, culture) as string;
        }
    }
}
